package com.chalk.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.chalk.common.constant.CommonConstants;
import com.chalk.common.util.Result;
import com.chalk.common.util.ResultCode;
import com.chalk.config.base.BaseController;
import com.chalk.config.security.JwtRedisUtil;
import com.chalk.config.security.JwtTokenUtils;
import com.chalk.model.Member;
import com.chalk.model.SysUser;
import com.chalk.service.MemberService;
import com.chalk.service.SysUserService;
import com.chalk.vo.MemberVo;
import com.chalk.vo.MyMemberVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 会员表(Member)表控制层
 *
 * @author maxiaoqiang
 * @since 2019-03-22 17:38:23
 */
@Api(value = "会员表接口", tags = "会员表模块")
@RestController
@RequestMapping("/v1/member")
public class MemberController extends BaseController {

    @Autowired
    private MemberService memberService;
    @Autowired
    private JwtRedisUtil jwtRedisUtil;

    @Autowired
    private SysUserService sysUserService;


    /**
     * 会员表列表
     *
     * @param current 当前页数
     * @param size    每页显示条数
     * @param member  查询实体
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "查询会员表列表", notes = "查询会员表列表", response = Result.class)
    @GetMapping
    public Result selectAll(Integer current, Integer size, Member member) {
        return Result.success(this.memberService.selectPage(this.getPage(current, size), new EntityWrapper<Member>(member)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "查询会员表", notes = "查询会员表", response = Result.class)
    @GetMapping("{id}")
    public Result selectOne(
            @ApiParam(name = "id", value = "主键", required = true, example = "1")
            @PathVariable String id) {
        return Result.success(this.memberService.selectById(id));
    }


    /**
     * 保存会员表
     *
     * @param member 实体对象
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "保存member", notes = "保存member", response = Result.class)
    @PostMapping
    public Result insert(
            @ApiParam(name = "member", value = "传入json格式", required = true)
            @RequestBody Member member) {
        DateTime date = DateUtil.date();
        member.setCreateTime(date);
        member.setUpdateTime(date);
        return Result.success(this.memberService.insert(member));
    }

    /**
     * 修改会员表
     *
     * @param member 实体对象
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "修改会员表", notes = "修改会员表", response = Result.class)
    @PutMapping
    public Result update(
            @ApiParam(name = "member", value = "传入json格式", required = true)
            @RequestBody Member member, HttpServletRequest request) {
        Member loginMember = memberService.selectUserDetail(request);
        if (loginMember == null){
            return  Result.notLogin();
        }
        member.setMemberId(loginMember.getMemberId());
        member.setUpdateTime(DateUtil.date());
        member.setPassword(null);
        member.setBlanace(null);
        member.setIntegral(null);
        // 审请商家 绑定手机号时  给系统管理用户添加绑定关系
        if (StringUtils.isNotBlank(member.getMobilePhone())){
            SysUser sysUser = sysUserService.selectOne(new EntityWrapper<SysUser>()
                    .eq("user_name", member.getMobilePhone())
                    .eq("is_deleted", CommonConstants.IsDeleted.NOTDEL.getValue()));
            if (null != sysUser){
                sysUser.setMemberId(loginMember.getMemberId());
            }
        }
        return Result.success(this.memberService.updateById(member));
    }

    /**
     * 逻辑删除会员表
     *
     * @param ids 主键集合
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "批量删除会员表", notes = "批量删除会员表", response = Result.class)
    @DeleteMapping
    public Result delete(
            @ApiParam(name = "ids", value = "传数组", required = true)
            @RequestBody String[] ids) {
        return Result.success(this.memberService.deleteBatchByPrimaryKey(ids));
    }

    private Page<Member> getPage(Integer current, Integer size) {
        Page<Member> page = new Page<>();
        if (current != null) {
            page.setCurrent(current);
        }
        if (size != null) {
            page.setSize(size);
        }
        return page;
    }


    /**
     * 获取用户ID
     *
     * @param request 主键集合
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "获取用户ID", notes = "获取用户ID", response = Result.class)
    @GetMapping("/getUserDetail")
    public Result getUserDetail(HttpServletRequest request) {
        Member userDetail = this.memberService.selectUserDetail(request);
        if (userDetail == null) {
            return Result.fail(ResultCode.USER_NOT_FOUND);
        } else {
            userDetail.setPassword(null);
            SysUser sysUser = sysUserService.selectOne(new EntityWrapper<SysUser>()
                    .eq("member_id", userDetail.getMemberId())
                    .eq("is_deleted", CommonConstants.IsDeleted.NOTDEL.getValue()));
            if(null != sysUser){
                userDetail.setSeller(true);
            }
            return Result.success(userDetail);
        }
    }

    /**
     * 修改密码
     *
     * @param member 实体对象
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "修改密码", notes = "修改密码", response = Result.class)
    @PostMapping("/updatePwd")
    public Result updatePwd(
            @ApiParam(name = "member", value = "传入json格式", required = true)
            @RequestBody MemberVo member) {
        return Result.success(this.memberService.updateMemberPwd(member));
    }

    /**
     * 平台用户信息注销
     *
     * @param request
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "退出登录", notes = "退出登录", response = Result.class)
    @DeleteMapping("/logout")
    public Result revokeToken(HttpServletRequest request) {
        String tokenHeader = request.getHeader(JwtTokenUtils.TOKEN_HEADER);
        // 如果请求头中没有Authorization信息则直接放行了
        if (tokenHeader == null || !tokenHeader.startsWith(JwtTokenUtils.TOKEN_PREFIX)) {
            return Result.fail(ResultCode.PARAM_IS_INVALID);
        }
        String username = JwtTokenUtils.getUsername(tokenHeader);
        if(StringUtils.isEmpty(username)){
            return Result.fail(ResultCode.USER_NOT_FOUND);
        }
        jwtRedisUtil.delRedisToken(username);
        jwtRedisUtil.delRefreshToken(username);
        return Result.success();
    }

    /**
     * 获取全部客户
     * @param page
     * @param size
     * @return
     */

    @ApiOperation(value = "我的客户",notes = "全部客户",response = Result.class)
    @PostMapping("/getMyMembers")
    public Result getMyMembers(@ApiParam(name ="page",value = "页码",required = true)
                              Integer page,@ApiParam(name ="size",value = "每页数量",required = true)Integer size
            ,@ApiParam(name ="有效/失效  0是有效 1是失效",value = "不传就全部客户",required = false)@RequestParam(required = false) Integer enable
    ){
        MyMemberVo myMemberVo=new MyMemberVo();
        myMemberVo.setPage(page);
        myMemberVo.setSize(size);
        myMemberVo.setEnable(enable);

        Member member = memberService.selectUserDetail(getRequest());
        if(member==null){
            return Result.notLogin();
        }
        if (member.getDistributorId()==null ||"".equals(member.getDistributorId())){
            return Result.success("对不起，你无法使用此接口，您不是分销商！");
        }
        myMemberVo.setMemberId(member.getMemberId());
        Result success = Result.success("获取成功！", memberService.getMyMembers(myMemberVo,member));
        return success;

    }

}